package com.zhida.gooutcrawler.activity;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zhida.gooutcrawler.R;
import com.zhida.gooutcrawler.entity.Column;
import com.zhida.gooutcrawler.entity.Page;
import com.zhida.gooutcrawler.service.SpiderService;
import com.zhida.gooutcrawler.spider.Spider;
import com.zhida.gooutcrawler.spider.SpiderListener;
import com.zhida.gooutcrawler.util.DialogUtil;
import com.zhida.gooutcrawler.util.FileUtil;
import com.zhida.gooutcrawler.util.ServiceUtil;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observable;
import rx.functions.Action1;

/**
 * 采集的activity
 * Created by ange on 2017/4/6.
 */

public class CrawlerActivity extends AppCompatActivity {


    @BindView(R.id.column_tags)
    TagFlowLayout mColumnTags;

    @BindView(R.id.column_url)
    TextView mColumnUrl;

    @BindView(R.id.column_name)
    TextView mColumnName;

    @BindView(R.id.loading)
    LinearLayout mLoading;

    @BindView(R.id.total_text)
    TextView mTotalText;

    @BindView(R.id.log_text)
    TextView mLogText;

    @BindView(R.id.start)
    Button mStart;

    @BindView(R.id.stop)
    Button mStop;

    @BindView(R.id.running_layout)
    LinearLayout mRunningLayout;

    @BindView(R.id.toolbar)
    Toolbar mToolbar;


    private List<Column> columns;

    private SpiderService.MyBinder spiderBinder;

    TagAdapter<Column> tagAdapter;

    private SpiderReceiver receiver;

    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            System.out.println("服务连接成功onServiceConnected,name:" + name);
            spiderBinder = ((SpiderService.MyBinder) service);
            onConnected();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            System.out.println("服务断开连接onServiceDisconnected,name:" + name);
        }
    };

    private SpiderListener spiderListener = new SpiderListener() {
        @Override
        public void onStartOne(String url) {
            Spider spider = spiderBinder.getSpider();
            if (spider.isRunning()) {
                mLoading.setVisibility(View.VISIBLE);
            } else {
                mLoading.setVisibility(View.GONE);
            }
        }

        @Override
        public void onFinishOne(Page page) {
            Spider spider = spiderBinder.getSpider();
            mTotalText.setText("已经采集了" + spider.getTotalCount() + "条");
            mLogText.setText("采集" + page.getUrl() + "完成");
        }

        @Override
        public void onFinishAll() {
            Spider spider = spiderBinder.getSpider();
            mLoading.setVisibility(View.GONE);
            mTotalText.setText("全部采集完成，共" + spider.getTotalCount() + "条");
            setContinueBtn();
        }
    };


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_crawler);
        ButterKnife.bind(this);
        init();
    }

    private void init() {
        initToolBar();
        initService();

        //加载所有栏目
        Observable.fromCallable(new Callable<List<Column>>() {
            @Override
            public List<Column> call() throws Exception {
                String json = FileUtil.getString(CrawlerActivity.this, "columns.json");
                Gson gson = new Gson();
                return gson.fromJson(json,
                        new TypeToken<List<Column>>() {
                        }.getType());
            }
        }).subscribe(new Action1<List<Column>>() {
            @Override
            public void call(List<Column> columns) {
                onInitColumns(columns);

            }
        });
    }

    @SuppressLint("SetTextI18n")
    public void initToolBar() {
        mToolbar.setTitle("");
        setSupportActionBar(mToolbar);
        /*ActionBar supportActionBar = getSupportActionBar();
        if (supportActionBar != null) {
            supportActionBar.setDisplayHomeAsUpEnabled(true);
        }*/
    }

    private void initService() {
        //bind services
        //绑定服务，同时不自动创建服务
        Intent bindIntent = new Intent(this, SpiderService.class);

        bindService(bindIntent, conn, BIND_AUTO_CREATE);

    }

    private void onInitColumns(List<Column> columns) {
        this.columns = columns;

        //初始化栏目数据
        tagAdapter = new TagAdapter<Column>(columns) {
            @Override
            public View getView(FlowLayout parent, int position, Column column) {
                TextView mTag = (TextView) LayoutInflater.from(CrawlerActivity.this)
                        .inflate(R.layout.tag_column, parent, false);
                mTag.setText(column.getText());
                return mTag;
            }
        };
        mColumnTags.setAdapter(tagAdapter);

        mColumnTags.setMaxSelectCount(1);

        //栏目被点击
        mColumnTags.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                Column item = tagAdapter.getItem(position);
                setColumnInfo(item);
                return false;
            }
        });
    }

    private void onConnected() {

        //star service onstart执行完毕触发
        spiderBinder.setBinderListener(new SpiderService.BinderListener() {
            @Override
            public void onStarted() {
                //设置监听器
                spiderBinder.getSpider().setSpiderListener(spiderListener);
            }
        });

        //检查是否点击了开始服务按钮
        if (spiderBinder.isServiceStarted()) {

            Column column = spiderBinder.getColumn();
            //选择flow tags
            Integer pos = -1;
            for (int i = 0; i < tagAdapter.getCount(); i++) {
                Column item = tagAdapter.getItem(i);
                if (item.getText().equals(column.getText())) {
                    pos = i;
                }
            }
            tagAdapter.setSelectedList(pos);


            Spider spider = spiderBinder.getSpider();
            if (spider.isRunning()) {

                setContinueBtn();
            } else {

                setPauseBtn();
            }

            //显示栏目url
            setColumnInfo(column);

            setPauseBtn();

        } else {


            System.out.println("服务已绑定未启动");
            setStartBtn();

        }

    }

    private void setColumnInfo(Column column){
        mColumnUrl.setText("栏目url:" + column.getHref());
        mColumnName.setText("选择栏目:" + column.getText());
    }

    private void setStartBtn() {
        mStart.setText("开始采集");
        mStop.setVisibility(View.GONE);
        mRunningLayout.setVisibility(View.GONE);
        mColumnTags.setEnabled(true);//不能选
    }

    private void setPauseBtn() {
        mStart.setText("暂停采集");
        mStop.setVisibility(View.VISIBLE);
        mRunningLayout.setVisibility(View.VISIBLE);
        mColumnTags.setEnabled(false);//不能选
    }

    private void setContinueBtn() {
        mStart.setText("继续采集");
        mColumnTags.setEnabled(false);//不能选
    }

    @OnClick({R.id.start, R.id.stop})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.start:

                if (spiderBinder.isServiceStarted()) {
                    //暂停服务
                    Spider spider = spiderBinder.getSpider();
                    if (spider.isRunning()) {
                        spider.pause();

                        setContinueBtn();
                    } else {
                        spider.start();

                        setPauseBtn();
                    }


                } else {
                    //启动服务

                    //获得选择的栏目
                    Set<Integer> selectedList = mColumnTags.getSelectedList();
                    if (selectedList.size() == 0) {
                        DialogUtil.confirm(CrawlerActivity.this, "请选择栏目");
                        return;
                    }
                    Integer index = selectedList.iterator().next();
                    Column column = columns.get(index);

                    SpiderService.start(this, column);
                    System.out.println("爬虫服务 SpiderService.start 之后");
                    setPauseBtn();
                }


                break;
            case R.id.stop:

//                unbindService(conn);
//                spiderBinder = null;
                Intent stopIntent = new Intent(this, SpiderService.class);
                stopService(stopIntent);
                spiderBinder.reset();

                setStartBtn();
                break;
        }
    }

    /*@OnClick({R.id.test})
    public void onClickTest(View view) {
        if (ServiceUtil.isWorked(this, SpiderService.class.getName())) {
            System.out.println("启动");
        } else {
            System.out.println("没有启动");
        }
    }*/

    class SpiderReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context arg0, Intent arg1) {
            String action = arg1.getAction();
            if (action.equals(SpiderService.FINISH_ONE)) {
                //从MusicService接收广播消息，弹出Toast
                String msg = arg1.getStringExtra("msg");
                Toast.makeText(CrawlerActivity.this, msg, Toast.LENGTH_SHORT)
                        .show();
            }
        }
    }

    @Override
    protected void onPause() {
        //注销BroadcastReceiver
        unregisterReceiver(receiver);
        super.onPause();
    }

    @Override
    protected void onResume() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(SpiderService.FINISH_ONE);

        if (receiver == null)
            receiver = new SpiderReceiver();
        //注册BroadcastReceiver
        registerReceiver(receiver, filter);
        super.onResume();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (spiderBinder != null) {
            unbindService(conn);
            if (spiderBinder.isServiceStarted()) {
                Spider spider = spiderBinder.getSpider();
                if (spider != null) {
                    spider.setSpiderListener(null);
                }
            }
        }
    }
}
